package com.xuebusi.toutiao.admin.api.comment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuebusi.toutiao.admin.api.article.entity.ArticleEntity;
import com.xuebusi.toutiao.admin.api.article.service.ArticleService;
import com.xuebusi.toutiao.admin.api.comment.dao.CommentDao;
import com.xuebusi.toutiao.admin.api.comment.entity.CommentEntity;
import com.xuebusi.toutiao.admin.api.comment.enums.CommentType;
import com.xuebusi.toutiao.admin.api.comment.service.CommentService;
import com.xuebusi.toutiao.admin.api.comment.vo.*;
import com.xuebusi.toutiao.admin.api.common.exception.CustomException;
import com.xuebusi.toutiao.admin.api.common.result.ApiResult;
import com.xuebusi.toutiao.admin.api.common.result.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 评论服务实现类
 */
@Slf4j
@Service("commentService")
public class CommentServiceImpl extends ServiceImpl<CommentDao, CommentEntity> implements CommentService {
    @Resource
    private ArticleService articleService;

    /**
     * 查询评论列表
     *
     * @param commentQuery 查询参数
     * @return
     */
    @Override
    public ResponseEntity<ApiResult<PageInfo<CommentEntity>>> getComments(CommentQueryPVO commentQuery) {
        long pageSize = commentQuery.getLimit();
        long current = commentQuery.getOffset() / pageSize + 1;
        Page<CommentEntity> page = new Page<>(current, pageSize);
        Page<CommentEntity> pageResult = this.page(page,
                new QueryWrapper<CommentEntity>()
                        .eq("type", commentQuery.getType())
                        .eq("source_id", commentQuery.getSource()));
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPage(current);
        pageInfo.setPer_page(pageSize);
        pageInfo.setTotal_count(pageResult.getTotal());
        pageInfo.setResults(pageResult.getRecords());
        return ResponseEntity.ok(ApiResult.ok(pageInfo));
    }

    /**
     * 创建评论
     *
     * @param userId    用户id
     * @param createPVO 评论表单
     * @return
     */
    @Override
    public ResponseEntity<ApiResult<CommentCreateRVO>> createComment(Integer userId, CommentCreatePVO createPVO) {
        ArticleEntity queryArticle = null;
        CommentEntity queryComment = null;
        // 查询文章
        if (createPVO.getArt_id() != null) {
            queryArticle = articleService.getById(createPVO.getArt_id());
        }
        // 查询评论
        if (createPVO.getTarget() != null) {
            queryComment = this.getById(createPVO.getTarget());
        }
        if (queryArticle == null && queryComment == null) {
            throw new CustomException("文章或评论不存在", 401);
        }
        CommentEntity commentEntity = new CommentEntity();
        commentEntity.setSource_id(createPVO.getArt_id());
        commentEntity.setAut_id(userId);
        commentEntity.setType(queryArticle != null ? CommentType.ART.getCode() : CommentType.COMMENT.getCode());
        commentEntity.setContent(createPVO.getContent());
        commentEntity.setPubdate(new Date());
        // 保存
        this.save(commentEntity);

        // 返回结果
        CommentCreateRVO createRVO = new CommentCreateRVO();
        createRVO.setCom_id(commentEntity.getId());
        createRVO.setTarget(createPVO.getTarget());
        createRVO.setArt_id(createPVO.getArt_id());
        return ResponseEntity.ok(ApiResult.ok(createRVO));
    }

    /**
     * 对评论或回复点赞
     *
     * @param userId 用户id
     * @param target 评论id或回复id
     * @return
     */
    @Override
    public ResponseEntity<ApiResult<CommentLikingRVO>> liking(Integer userId, Integer target) {
        CommentEntity commentEntity = new CommentEntity();
        commentEntity.setId(target);
        commentEntity.setAut_id(userId);
        commentEntity.setIs_liking(true);
        this.updateById(commentEntity);
        CommentLikingRVO likingRVO = new CommentLikingRVO(target);
        return ResponseEntity.ok(ApiResult.ok(likingRVO));
    }

    /**
     * 取消对评论或回复的点赞
     *
     * @param userId 用户id
     * @param target 要取消点赞的评论id或评论回复id
     * @return
     */
    @Override
    public ResponseEntity cancelLiking(Integer userId, Integer target) {
        CommentEntity commentEntity = new CommentEntity();
        commentEntity.setId(target);
        commentEntity.setIs_liking(false);
        this.updateById(commentEntity);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除评论或回复
     *
     * @param userId 用户id
     * @param target 评论或回复 id
     * @return
     */
    @Override
    public ResponseEntity deleteComment(Integer userId, Integer target) {
        log.info(">>> deleteComment, userId:{}, target:{}", userId, target);
        CommentEntity commentEntity = this.getById(target);
        if (commentEntity == null) {
            throw new CustomException("评论不存在", 401);
        }
        // TODO 检查是否具有删除权限
        this.removeById(target);
        return ResponseEntity.noContent().build();
    }

    /**
     * 修改评论置顶
     *
     * @param userId 用户id
     * @param target 评论或回复id
     * @param sticky 是否置顶
     */
    @Override
    public ResponseEntity<ApiResult<CommentStickyRVO>> updateIsTop(Integer userId, Integer target, Boolean sticky) {
        log.info(">>> update is top, userId:{}, target:{}, sticky:{}", userId, target, sticky);
        CommentEntity queryEntity = this.getById(target);
        if (queryEntity == null) {
            throw new CustomException("评论不存在", 401);
        }
        CommentEntity commentEntity = new CommentEntity();
        commentEntity.setId(target);
        commentEntity.setIs_top(sticky);
        this.updateById(commentEntity);
        CommentStickyRVO stickyRVO = new CommentStickyRVO(target, sticky);
        return new ResponseEntity(ApiResult.ok(stickyRVO), HttpStatus.CREATED);
    }
}
